package org.devocean.groupbuying.utils;

import org.apache.tiles.AttributeContext;
import org.apache.tiles.context.TilesRequestContext;
import org.apache.tiles.preparer.ViewPreparer;
import org.devocean.groupbuying.service.CustomerService;
import org.devocean.groupbuying.service.MenuService;
import org.devocean.groupbuying.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;

@Component
public class MenuAction implements ViewPreparer {

	@Autowired
	private CustomerService customerService;

	@Autowired
	private MenuService menuService;

	public void execute(TilesRequestContext requestContext,
			AttributeContext context) {
		final String lang = requestContext
				.getRequestScope()
				.get("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE")
				.toString();

		SecurityContext sc = (SecurityContext) requestContext.getSessionScope()
				.get("SPRING_SECURITY_CONTEXT");

		if (sc != null) {
			requestContext.getRequestScope().put(
					"user",
					customerService.getCustomerById(Integer.valueOf(sc
							.getAuthentication().getName())));
		}

		requestContext.getRequestScope().put("menus",
				menuService.getAllMenus(lang));

	}
}
